package com.bng8.superstar_cms.interceptor;

import com.bng8.superstar_cms.exception.BusinessException;
import com.bng8.superstar_cms.exception.ErrorCodeEnum;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * ClassName: RateLimitInterceptor
 * Package: com.bng8.superstar_cms.interceptor
 * Date: 2023/8/15 9:14
 * Author: 安知（13921877634）
 */
@Component
@Slf4j
public class RateLimitInterceptor implements HandlerInterceptor {
    /**
     * 限流器实例(QPS限制为1)
     */
    private static final RateLimiter rateLimiter = RateLimiter.create(2);

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        // 尝试获取令牌
        if (!rateLimiter.tryAcquire()) {
            log.error("系统已被限流，请稍后再试...");
            throw new BusinessException(ErrorCodeEnum.RATE_LIMIT_ERROR);
        }
        return true;
    }
}
